package com.lancoo.answer.view.fragment.paragraphSort

import android.content.Context
import android.os.Bundle
import android.view.View
import androidx.fragment.app.Fragment
import com.lancoo.answer.R
import com.lancoo.answer.component.InteractWebView
import com.lancoo.answer.databinding.EvFragmentCommonBinding
import com.lancoo.answer.model.AnswerConstant
import com.lancoo.answer.model.ConstantBean
import com.lancoo.answer.model.ConstantBean.Companion.constantExamBean
import com.lancoo.answer.model.TaskState
import com.lancoo.answer.model.bean.Ques
import com.lancoo.answer.view.base.BaseVMFragment
import com.lancoo.answer.widget.SplitView
import com.rxjava.rxlife.ObservableLife
import com.rxjava.rxlife.RxLife
import io.reactivex.Observable
import io.reactivex.Single
import io.reactivex.android.schedulers.AndroidSchedulers
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.util.concurrent.TimeUnit

/**
 * Created by Dadong on 2021/12/15
 * Describe: 段落排序、多项对应
 */
class ParagraphSortingFragment : BaseVMFragment<EvFragmentCommonBinding>() {

    private val TAG = "ParagraphSortingFragmen"
    private lateinit var ques: Ques
    private var typeIndex = 0
    private var quesIndex = 0
    private var defaultLoadIndex = 0
    private lateinit var paragraphSortingChildFragment: ParagraphSortingChildFragment
    private lateinit var convertView:View

    companion object {
        fun loadFragment(typeIndex: Int, quesIndex: Int, defaultLoadIndex: Int): Fragment? {
            val mBundle = Bundle()
            mBundle.putInt(AnswerConstant.KEY_TYPEINDEX, typeIndex)
            mBundle.putInt(AnswerConstant.KEY_QUESINDEX, quesIndex)
            mBundle.putInt(AnswerConstant.KEY_LOADCHILDINDEX, defaultLoadIndex)
            val paragraphSortingFragment = ParagraphSortingFragment()
            paragraphSortingFragment.arguments = mBundle
            return paragraphSortingFragment
        }
    }

    override fun getLayoutId(): Int {
        return R.layout.ev_fragment_common
    }

    override fun initView(view: View) {
        convertView = view
        EventBus.getDefault().register(this)
        val kindBeanList = constantExamBean!!.TypeList
        typeIndex = requireArguments().getInt(AnswerConstant.KEY_TYPEINDEX)
        quesIndex = requireArguments().getInt(AnswerConstant.KEY_QUESINDEX)
        defaultLoadIndex = requireArguments().getInt(AnswerConstant.KEY_LOADCHILDINDEX)
        ques = kindBeanList!![typeIndex].QuesList!![quesIndex]
    }

    override fun initData() {
        mBinding.interactWv.initWebView(
            requireActivity(),
            ques.QuesBody!!,
            object : InteractWebView.Callback {
                override fun clickCallback(position: String) {
                }

                override fun finishCallback() {
                    adjustFontSize()
                    initLayout()
                    if (ConstantBean.taskState == TaskState.TRAINING) {
                        Observable.timer(200, TimeUnit.MILLISECONDS) //必须加延时才能算准高度
                            .observeOn(AndroidSchedulers.mainThread())
                            .`as`<ObservableLife<Long>>(RxLife.`as`<Long>(this@ParagraphSortingFragment))
                            .subscribe { aLong: Long? ->
                                if (arguments == null) {
                                    return@subscribe
                                }
                                openPalette()
                            }
                    }
                }

            }
        )
        initAnswer()
    }

    private fun openPalette() {
        val sharedPreferences =
            requireContext().getSharedPreferences(AnswerConstant.SP_ANSWER_NAME, Context.MODE_PRIVATE)
        val openDash = sharedPreferences.getBoolean(AnswerConstant.SP_OPEN_DASH, false)
        if (openDash) {
            mBinding.interactWv.openPalette()
        } else {
            mBinding.interactWv.closePalette()
        }
    }

    private fun initAnswer() {
        paragraphSortingChildFragment =
            ParagraphSortingChildFragment.loadFragment(typeIndex, quesIndex, defaultLoadIndex)
        childFragmentManager
            .beginTransaction()
            .replace(mBinding.flAnswer.id, paragraphSortingChildFragment!!, TAG)
            .commit()
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onGetPosition(position: Int?) {
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }

    /**
     * 跳转到指定小题
     * @param itemIndex 答题点下标
     */
    fun jumpToAimChildFragment(itemIndex: Int) {
        if (childFragmentManager != null &&
            mBinding != null
        ) {
            val fragment = childFragmentManager.findFragmentByTag(TAG)
            if (fragment is ParagraphSortingChildFragment) {
                fragment.setCurrentItem(itemIndex)
            }
        }
    }

    fun getItemIndex(): Int {
        if (childFragmentManager != null &&
            mBinding != null
        ) {
            val fragment = childFragmentManager.findFragmentByTag(TAG)
            if (fragment is ParagraphSortingChildFragment) {
                return fragment.getRealIndex()
            }
        }
        return 0
    }

    fun adjustFontSize() {
        mBinding.interactWv.setFontSize()
        paragraphSortingChildFragment.adjustFontSize()
    }

    fun markQuestion() {
        paragraphSortingChildFragment.markQuestion()
    }

    fun initLayout() {
        if (convertView == null) {
            return
        }
        val splitView: SplitView = convertView!!.findViewById<SplitView>(R.id.split_view)
        Single.timer(250, TimeUnit.MILLISECONDS)
            .observeOn(AndroidSchedulers.mainThread())
            .`as`(RxLife.`as`(this))
            .subscribe({ splitView.initLayout(0.5f) }) { throwable: Throwable? -> }
    }
}